package net.zjitc.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 拦截的是什么？ 通过urlPatterns配置
 */
@WebFilter(filterName = "GoodsFilter" ,urlPatterns = "/*")
public class GoodsFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;

       //如果请求的地址是/login，直接放行
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/login") || requestURI.contains("/bootstrap-3.4.1-dist/") ||requestURI.contains("/index.jsp")
                ||requestURI.endsWith("/")){
            chain.doFilter(req,resp);
        }else {
            //判是否登录，如果登录，放行，否则转到login.jsp
            Object user = request.getSession().getAttribute("user");
            if (user!=null){//放行
                chain.doFilter(req,resp);
            }else {
                //转到登录
                request.setAttribute("msg","请先登录！");
                RequestDispatcher dispatcher = request.getRequestDispatcher("/login/login.jsp");
                dispatcher.forward(req,resp);
            }
        }

        //chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
